import useMainInvoke from './useMainInvoke'
import useMinWaitPromise from './useMinWaitPromise'
import useRendererListen from './useRendererListen'

/**
 * @description 用于主线程和渲染线程之间的通信
 */
interface InteractionConfig {
  type: string
  eventName: string
  data?: any
  suffix?: string // 事件完成后的名称尾缀
  minWait?: number // 最小等待时间
}
export default function useInteraction<T>(config: InteractionConfig): Promise<T> {
  return new Promise((resolve) => {
    const id = Math.random().toString()
    const lastTime = Date.now()

    useRendererListen(`${config.eventName}-${config.suffix ?? 'done'}`, id, (event: T) => {
      useMinWaitPromise<T>(lastTime, event, config.minWait).then((result) => {
        resolve(result!)
      })
    })

    useMainInvoke(config.type, config.eventName, { ...(config.data ?? {}), id })
  })
}
